package com.csq.manager.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.csq.common.pojo.EasyUIDataGridResult;
import com.csq.common.pojo.ReturnResult;
import com.csq.common.pojo.StatusCode;
import com.csq.common.util.JsonUtils;
import com.csq.manager.mapper.AccountMapper;
import com.csq.manager.pojo.Account;
import com.csq.manager.pojo.AccountExample;
import com.csq.manager.pojo.AccountExample.Criteria;
import com.csq.manager.service.AccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private PoolJedisClient poolJedisClient;

	@Value("${SESSON_KEY}")
	private String SESSON_KEY;

	@Value("${SESSON_EXPIE}")
	private int SESSON_EXPIE;

	@Override
	public Account getAccountByID(Integer userId) {
		// TODO Auto-generated method stub

		Account account = accountMapper.selectByPrimaryKey(userId);

		return account;
	}

	@Override
	public EasyUIDataGridResult getAccountList(Integer page, Integer rows) {

		AccountExample accountExample = new AccountExample();

		PageHelper.startPage(page, rows);

		List<Account> list = accountMapper.selectByExample(accountExample);

		PageInfo<Account> pageInfo = new PageInfo<>(list);

		EasyUIDataGridResult easyUIDataGridResult = new EasyUIDataGridResult();

		easyUIDataGridResult.setRows(list);
		easyUIDataGridResult.setTotal(pageInfo.getTotal());

		// TODO Auto-generated method stub
		return easyUIDataGridResult;
	}

	@Override
	public List<Account> getAllAccountList(Integer typeId) {
		AccountExample accountExample = new AccountExample();
		if (typeId != 2) {
			Criteria createCriteria = accountExample.createCriteria();
			createCriteria.andStateEqualTo(typeId.shortValue());
		}
		return accountMapper.selectByExample(accountExample);
	}

	@Override
	public ReturnResult updateAccount(Account account) {
		// TODO Auto-generated method stub

		System.out.println("service:" + account);

		int updateByPrimaryKeySelective = accountMapper
				.updateByPrimaryKeySelective(account);

		if (updateByPrimaryKeySelective == 0) {
			return ReturnResult.build(StatusCode.UPDATEFAIL, "更新失败！！");
		}

		account = accountMapper.selectByPrimaryKey(account.getUserId());

		String token = account.getEmail();

		// 更新 redis 缓存
		poolJedisClient.set(SESSON_KEY + ":" + token,
				JsonUtils.objectToJson(account));

		poolJedisClient.expire(SESSON_KEY + ":" + token, SESSON_EXPIE);

		return ReturnResult.ok();
	}

}
